<script setup lang="ts">
import { getBannerListFn, getNavListFn, getProListFn } from '@/api/home.ts'
import { onMounted, reactive, ref, onDeactivated, onActivated } from 'vue'
import type { iState } from './indexType'
import { useRouter, useRoute } from 'vue-router'
import proCom from '@/components/proCom.vue'
import type { Ref } from 'vue'

import { useUserInfoStore } from '@/stores/user'
const userInfoStore = useUserInfoStore()

// 带 r 的是路由跳转方法
const router = useRouter()
// 不带 r 的是路由跳转的信息
const route = useRoute()
// console.log(route);



const state: iState = reactive({
    bannerList: [],
    navList: getNavListFn(),
    // 添加一个商品列表的数据
    proList: []
})


onMounted(() => {
    getBannerListFn().then((res) => {
        // console.log(res);
        state.bannerList = res.data.data
    })

    // 发送数据请求获取到商品列表
    getProListFn(1).then(res => {
        // console.log(res);
        state.proList = res.data.data
    })
})

function loginClick() {
    router.push('/login')
}

function logoutClick() {
    userInfoStore.changeUserInfo({
        token: '',
        userid: ''
    })
}


// ----------------- 上拉加载更多
// 定义当前页码
let count = 2
const loading: Ref<boolean, boolean> = ref(false)
const finished: Ref<boolean, boolean> = ref(false)
// 发送数据请求的方法
function onLoad() {
    // console.log(1111111111);
    loading.value = true

    // 发送数据请求获取到商品列表
    getProListFn(count).then(res => {

        if (res.data.data.length <= 0) {
            finished.value = true
        } else {
            state.proList = [...state.proList, ...res.data.data]
            count++
            loading.value = false
        }


    })
}
// ----------------- 点击回到顶部
const top: Ref<number, number> = ref(0)
function scrollTop(event: any) {
    // console.log(event?.target.scrollTop);
    top.value = event?.target.scrollTop
}
const contentRef = ref()
function goTopClick() {
    // top.value = 0
    // console.log(contentRef.value);
    contentRef.value.scrollTop = 0
    // 设置滚动位置为 0
    // let time: any = 0
    // clearInterval(time)
    // time = setInterval(() => {
    //     contentRef.value.scrollTop = contentRef.value.scrollTop - 20
    //     if (contentRef.value.scrollTop <= 0) clearInterval(time)
    // }, 1)
}
// ------------------ 点击回到顶部
// ------------------ 下拉刷新
// 是否在下拉刷新
const pullRefresh: Ref<boolean, boolean> = ref(false)
function onRefresh() {
    pullRefresh.value = true
    // 1. 重新获取最新的数据
    getProListFn(1).then(res => {
        // console.log(res);
        state.proList = res.data.data

        // 关闭下拉刷新的状态
        pullRefresh.value = false
    })

    // 2. 清除原来上拉加载更多的页码
    count = 2

    // 3. 清除原来上拉加载更多的其余状态(是否还有更多数据)
    loading.value = false
    finished.value = false
}


// ---------- 返回到指定位置
// 监听离开页面，在离开页面的时候记录当前的滚动位置
onDeactivated(() => {
    // 1. 先获取当前页面的滚动位置
    console.log('监听离开页面' + top.value);
    // 2. 将当前的滚动位置保存在本地
    sessionStorage.setItem('top', String(top.value))

})
// 监听再次回到页面，回到页面的时候取出记录的位置，然后设置到指定位置即可
onActivated(() => {

    // 3. 获取到保存的滚动位置
    console.log('监听再次回到页面' + sessionStorage.getItem('top'));

    // 4. 将滚动距离设置在页面的 content 上
    contentRef.value.scrollTop = Number(sessionStorage.getItem('top'))

    // 5. 清除保存的滚动距离
    sessionStorage.removeItem('top')

})
</script>
<template>
    <main class="box">
        <header class="header">
            <span>头部-首页</span>

            <van-button v-if="userInfoStore.userinfo.token == ''" @click="loginClick" size="mini"
                type="primary">登录</van-button>
            <van-button v-else @click="logoutClick" size="mini" type="primary">退出登录</van-button>
        </header>

        <!-- contentRef 虽然是定义的，但是这里不能加 : -->
        <div @scroll="scrollTop" ref="contentRef" class="content">
            <van-pull-refresh @refresh="onRefresh" v-model="pullRefresh">
                <!-- 轮播图模块 -->
                <van-swipe class="my-swipe" :autoplay="3000" indicator-color="#f66">
                    <van-swipe-item :key="item.bannerid" v-for="item in state.bannerList">
                        <img :src="item.img" alt="">
                    </van-swipe-item>
                </van-swipe>

                <!-- 宫格模块 -->
                <van-grid icon-size=".28rem" column-num="5">
                    <van-grid-item :key="item.navid" v-for="item in state.navList" :icon="item.imgurl">
                        <template #text="scoped">
                            <span class="a">{{ item.title }}</span>
                        </template>
                    </van-grid-item>
                </van-grid>

                <!-- 渲染商品列表 -->
                <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                    <proCom :pro-list="state.proList"></proCom>
                </van-list>


                <div @click="goTopClick" class="back-top" v-show="top > 300">
                    <van-icon size="28" name="back-top" />
                </div>
            </van-pull-refresh>
        </div>

    </main>
</template>

<style scoped lang="scss">
.my-swipe .van-swipe-item {
    color: #fff;
    font-size: 20px;
    height: 2rem;
    line-height: 2rem;
    text-align: center;
    background-color: #39a9ed;

    img {
        width: 100%;
        height: 100%;

    }
}

.header {

    .van-button {
        float: right;
        position: relative;
        left: -10px;
        top: 10px;
    }
}

.back-top {
    position: fixed;
    bottom: 1.1rem;
    right: 10px;
    width: .42rem;
    height: .42rem;
    background-color: white;
    border: 1px solid #f66;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.content {
    // 设置平滑滚动
    scroll-behavior: smooth;
}
</style>